import React, { PureComponent, Fragment } from 'react';
import { connect } from 'react-redux';

import { Layout } from 'antd';
import {
    PageHeader,
    Table,
    ButtonEvent,
    SearchForm,
    Tree,
    Tip,
    Modal,
    Drawer,
    Form
} from '../../../components';
import { mainService } from '../../../service';
import { cmsNewAction as actionCreates, mainAction } from '../../../store/action';
import { Luck } from '../../../utils';

import "./index.less";

const breadcrumbList = [{
    title: '内容管理'
}, {
    title: '文章管理'
}];

const searchdata = [
    {type:'input',title:'标题',name:'like__title',value:'',placeholder:"请输入标题"}
];

class Index extends PureComponent{
    state = {
        //api名称
        apiname:'cms/article',
        //设置表单按钮
        tableBtn:[
            {key:1,type:'primary',value:'添加',onClick:()=>{ this.openModel('add'); }},
            {key:2,type:'default',value:'批量移动',onClick:()=>{ this.openModel('move'); }},
            {key:3,type:'danger',value:'删除',onClick:()=>{ this.openModel('del'); }}
        ],
        //表格colums
        columns:[
            {title: 'ID',dataIndex: 'id',width:80 }
            ,{title: '标题',dataIndex: 'title',width:300 }
            /*,{title: '标题颜色',dataIndex: 'color',width:80,className:"color-box",render:(value)=>{
                return <span className="color-block" style={{backgroundColor:value}}></span>
            }}*/
            ,{title: '作者',dataIndex: 'author',width:120 }
            ,{title: '发布时间',dataIndex: 'create_time',width:150,sorter:true,render:(value)=>Luck.tamptotime(value,'m') }
            ,{title: '阅读量',dataIndex: 'click',width:100,sorter:true }
            ,{title: '已有标签',dataIndex: 'tags',width:150 }
            ,{title: '选择标签',key: 'tag',width:100,render:(value)=><ButtonEvent data={ [
                {key:1,value:'选择标签',type:"primary",size:'small',onClick:()=>{
                    this.choseTag(value)
                }}
            ]}/>}
            ,{title: '更新时间',dataIndex: 'update_time',width:150,sorter:true,render:(value)=>Luck.tamptotime(value,'m') }
            ,{ title: '操作', key: 'operation',fixed:'right', width: 150, render: (value) =><ButtonEvent data={ [
                {key:1,value:'修改',size:'small',onClick:()=>{
                    this.edit(value)
                }},
                {key:2,type:'danger',value:'删除',size:'small',onClick:()=>{
                    this.del(value)
                }}
            ]}/> }
        ],

        //选中数据
        selectedRowKeys:[],
        selectedRows:[],
        selectedIds:[],
        pagination : {
            current:1,
            onShowSizeChange:(cur,pageSize)=>{this.changeRowsPage(cur,pageSize)},
        },
        cid:0,

        modalTitle:"",
        inputdata : [],
        footerbar:null,

        modelVisible:false,
        modelFooterbar:null,
        modelInputData:[],
    }
    render(){
        const { loading, list, emptyText, total, pageSize, page, cates, defcateid } = this.props;
        const { tableBtn, columns, pagination, selectedRowKeys } = this.state;
        pagination.total = total;
        pagination.current = page;
        pagination.pageSize=pageSize;
        
        const locale = {
            emptyText
        }
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange
        }

        const action = <ButtonEvent data={ [
            {key:1,type:'primary',value:'刷新',size:'small',onClick:()=>{
                this.refresh()
            }}
        ]}/>;

        //弹窗需要的
        const { visible, modalTitle, inputdata, footerbar } = this.state;
        const { modelVisible, modelFooterbar, modelInputData } = this.state;
        let modelData=modelInputData;
        
		modelData.map((item)=>{
			if(item["name"]==="cid"){
				item["treeData"]=cates;
			}
			return item;
        })

        return(
            <Fragment>
                <PageHeader title={breadcrumbList[1]['title']} breadcrumbList={breadcrumbList} action={action}></PageHeader>

                <Layout.Content style={{margin:'24px 0',backgroundColor:'#fff',display:'block',overflow:"hidden"}}>
                    
                    <Layout.Content className="article_tree">
                        <h2>分类(选择后查看文章列表)</h2>
                        <div className="article_ul">
                            <Tree
                                expandedKeys={defcateid}
                                onSelect={this.onTreeSelect}
                                data={cates}
                            />
                        </div>
                    </Layout.Content>
                    <Layout.Content className="article_list">
                        <SearchForm
                            style={{ marginBottom: 16 }}
                            layout = 'inline'
                            data={searchdata}
                            reset={this.refresh}
                            submit={this.search}
                            wrappedComponentRef={(form) => this.searchRef = form}
                        />

                        <ButtonEvent
                            data={ tableBtn }
                            style={{marginBottom:16}}
                        />
                        <Table
                            columns = {columns}
                            dataSource = { list }
                            locale = {locale}
                            loading = { loading }
                            rowSelection={ rowSelection }
                            onChange = { this.handleChange }
                            pagination ={ pagination }
                        />
                    </Layout.Content>
                </Layout.Content>

                <Drawer
                    title={modalTitle}
                    visible={visible}
                    footBar={footerbar}
                    destroyOnClose={true}
                    maskClosable={true}
                    onClose={this.handleCancel}
                    width="400px"
                >
                    <Form
                        layout = 'horizontal'
                        data = {inputdata}
                        wrappedComponentRef={(form) => this.formRef = form}
                    />
                </Drawer>

                <Modal
                    visible={modelVisible}
                    title = "批量移动到指定栏目"
                    onCancel={this.modelCancel}
                    maskClosable={false}
                    footer={ modelFooterbar }
                    destroyOnClose={true}
                    drag={true}
                    className="modal-top"
                >
                    <Form
                        layout = 'horizontal'
                        data = {modelData}
                        wrappedComponentRef={(form) => this.formModelRef = form}
                    />
                </Modal>
            </Fragment>
        )
    }
    choseTag = async (obj)=>{
        const { apiname } = this.state;
        let res = await mainService.find(apiname+"/gettags",{
            article_id:obj.id
        });
        if(res.code !== 0){
            Tip.Message("没获取到标签，请重试！",'error');
            return false;
        }
        let data = res.data;
        let footerbar = [{key:1,value:'取消',onClick:()=>{
            this.handleCancel();
        }},{key:2,type:'primary',value:'保存',btnloading:"1",onClick:()=>{ this.saveTags(); }}];
        
        let checkedData = data['checked']? data['checked']["tag_ids"] || "" :"";
        let formData = [
            {type:'input.hidden',title:'articleId',name:'article_id',value:obj.id,disabled:true},
            {type:'input.treeselect.hide',title:'标签',name:'tag_ids',childname:'tag_ids',value:checkedData,data:data['all']},
        ];

        this.setState({
            modalTitle:'选择标签',
            visible:true,
            footerbar,
            inputdata:formData
        });
    }
    saveTags = async ()=>{
        const { apiname } = this.state;
        const { bindLoading, pageSize, page } = this.props;
        let values = await this.formRef.getItemsValue();
        if(values){
            try{
                let res = await mainService.crud(apiname+"/settags",values);
                if(res.code===0){
                    this.handleCancel();
                    Tip.Message(res.msg,'success');
                    bindLoading(true);
                    this.loadList({page,rows:pageSize})
                }else{
                    Tip.Message(res.msg,'error')
                }

            }catch{
                Tip.Message("网络错误",'error')
            }
        }
        setTimeout(()=>{
            this.changeBtnLoading(false);
        },500);
    }
    
    //保存按钮状态
    changeBtnLoading = (bool)=>{
        this.props.bindBtnLoading(bool)
    }
    //关闭弹窗
    handleCancel=()=>{
        this.setState({
            visible:false
        })
    }
    //关闭弹窗
    modelCancel=()=>{
        this.setState({
            modelVisible:false
        })
    }

    //获取列表
    async loadList(data){
        const { bindList, bindPage } = this.props;
        const { apiname, cid } = this.state;
        data['cid'] = cid;
        if(!data.hasOwnProperty('order')){
            data['field'] = 'create_time';
            data['order']='desc';
        }
        let res = await mainService.getlist(apiname,data);
        bindList(res);
        bindPage(data.page);
    }

    //查询数据
    search = (name)=>{
        const { bindLoading, bindPage, pageSize } = this.props;
        bindLoading(true)
        this.loadList({page:1,rows:pageSize,...name})
        bindPage(1);
    }
    //重置查询
    refresh = () => {
        const { bindLoading, pageSize, page } = this.props;
        bindLoading(true)
        this.loadList({page,rows:pageSize})
        
    }
    
    edit = (obj)=>{
        const { bindLoading, pageSize, page } = this.props;
        let w=window.screen.width-10;
        let h=window.screen.height-95;
        const win=window.open('about:blank','',"left=10,top=10,width=" + w + ",height=" + h + ",toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no");
        let paramUrl='/'+obj.id;
        win.location.href='/cms/article/edit'+paramUrl;

        let loop = setInterval(()=>{   
            if(win.closed) {  
                clearInterval(loop);  
                
                bindLoading(true)
                this.loadList({page,rows:pageSize}) 
            }  
        }, 1000);
    }

    del = (obj)=>{
        let id=[];
        id.push(obj.id)
        this.delete(id);
    }
    //openModel
    openModel=(type)=>{
        const { selectedIds, cid } = this.state;
        //刷新
        const { bindLoading, pageSize, page } = this.props;
        switch (type) {
            case 'add':
                let w=window.screen.width-10;
                let h=window.screen.height-95;
                const win=window.open('about:blank','',"left=10,top=10,width=" + w + ",height=" + h + ",toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no");
                let paramUrl=cid!==0?'/'+cid:"";
                win.location.href='/cms/article/add'+paramUrl;
                //this.props.history.replace('/cms/article/add');

                let loop = setInterval(()=>{   
                    if(win.closed) {  
                        clearInterval(loop);  
                        
                        bindLoading(true)
                        this.loadList({page,rows:pageSize}) 
                    }  
                }, 1000);
                break;
            case 'del':
                if(selectedIds.length > 0){
                    this.delete(selectedIds);
                }else{
                    Tip.Message('至少选择一条数据进行删除','error')
                }
                break;
            case 'move':
                if(selectedIds.length > 0){
                    this.move(selectedIds);
                }else{
                    Tip.Message('至少选择一条数据进行移动','error')
                }
                break;
            default:
                break;
        }
    }
    delete = (arr)=>{
        const { apiname } = this.state;
        Tip.Modal('您真的要删除?','confirm',{
            onOk:async ()=>{
                let res = await mainService.crud(apiname+"/del",arr);
                this.tipMsg(res,'del');
            }
        })
    }
    move = (arr)=>{
        //const { apiname } = this.state;
        let modelInput = [
            {type:'select.treeopen',title:'栏目',name:'cid',placeholder:"请选择目标栏目",treeData:[],rules:[{
                required: true,
                message: '栏目不能为空'
            }]},
        ];

        this.setState({
            modelInputData:modelInput,
            modelVisible:true,
            modelFooterbar:
            <ButtonEvent data={[
                {key:1,value:'取消',onClick:this.modelCancel},
                {key:2,type:'primary',value:'保存',btnloading:"1",onClick:()=>{
                    this.saveMove(arr)
                }}
            ]}/>
        });
    }
    //保存数据
    saveMove = async (arr)=>{
        const {apiname} = this.state;

        let modelValue = await this.formModelRef.getItemsValue();
        if(modelValue){
            this.changeBtnLoading(true);
            modelValue['article_id'] = arr;
            try{
                let res = await mainService.crud(apiname+"/move",modelValue);
                this.tipMsg(res);
                this.setState(()=>({
                    selectedIds:[],
                    selectedRowKeys:[]
                }))
            }catch{
                this.tipMsg({code:3,msg:"网络错误"});
            }
        }
        setTimeout(()=>{
            this.changeBtnLoading(false);
        },500);
    }
    //消息提示
    tipMsg = (res,type='')=>{
        const { bindLoading, bindPage, pageSize, page } = this.props;
        if(res.code===0){
            this.modelCancel();
            Tip.Message(res.msg,'success');
            bindLoading(true)
            if(type==='del'){
                this.loadList({page:1,rows:pageSize})
                bindPage(1);
            }else{
                this.loadList({page,rows:pageSize})
            }
        }else{
            Tip.Message(res.msg,'error')
        }
    }

    //排序和翻页
    handleChange = (pagination, filters, sorter)=>{
        const { bindLoading } = this.props;
        let values = this.searchRef.getItemsValue();
        let order={};
        if(Object.keys(sorter).length>0){
            order={
                field:sorter.field,
                order:sorter.order==="descend" ? 'desc':'asc'
            }
        }
        bindLoading(true)
        this.loadList({page:pagination.current,rows:pagination.pageSize,...order,...values})
    }
    //每页条数
    changeRowsPage = (cur,pagesize)=>{
        const { bindPageSize } = this.props;
        bindPageSize(pagesize);
    }
    //选择
    onSelectChange=(selectedRowKeys, selectedRows) => {
        let newselectedRows=[];
        let selectedIds=[];
        for (let i = 0; i < selectedRows.length; i++) {
            newselectedRows.push(selectedRows[i]);
            selectedIds.push(selectedRows[i].id);
        }
        this.setState({ 
            selectedRowKeys,
            selectedRows:newselectedRows,
            selectedIds
        });
    }

    getCates = async ()=>{
        const { apiname } = this.state;
        const { bindCates } = this.props;
        let res = await mainService.getlist(apiname+'/getcate');
        bindCates(res);
    }
    onTreeSelect = (item)=>{
        let cid = 0;
        if(item.length>0){
            cid = parseInt(item[0]);
        }
        this.setState({
            cid
        },()=>{
            const { pageSize, bindLoading } = this.props;
            let values = this.searchRef.getItemsValue();
            bindLoading(true)
            this.loadList({page:1,rows:pageSize,...values});
        })
    }
    componentDidMount(){
        const { pageSize, page } = this.props;
        this.getCates();
        this.loadList({page,rows:pageSize});
    }
}
const mapStateToProps = (state)=>{
    const name = 'cms_new';
    const list = state.getIn([name,'list']).toJS();
    const loading = state.getIn([name,'loading']);
    const total = state.getIn([name,'total'])
    const emptyText = state.getIn([name,'emptyText']);
    
    const page = state.getIn([name,'page']);
    const pageSize = state.getIn([name,'pageSize']);
    const cates = state.getIn([name,'cates']).toJS();
    const defcateid = state.getIn([name,'defcateid']).toJS();

    const btnloading = state.getIn(['main','btnloading']);


    return{
        list,
        loading,
        total,
        emptyText,
        cates,
        defcateid,

        page,
        pageSize,
        btnloading
    }
}
const mapDispatchToProps = (dispatch)=>{
    return{
        bindLoading(loading){
            dispatch(actionCreates.setLoading(loading))
        },
        bindPageSize(pageSize){
            dispatch(actionCreates.setPagesize(pageSize));
        },
        bindPage(page){
            dispatch(actionCreates.setPage(page));
        },
        bindList(res){
            if(res.code === 0){
                let list=res.data;
                dispatch(actionCreates.getList(list.rows,list.total));
            }else{
                dispatch(actionCreates.setEmptyText(res.msg));
            }
            dispatch(actionCreates.setLoading(false));
        },
        bindBtnLoading(bool){
            dispatch(mainAction.setBtnLoading(bool));
        },
        bindCates(res){
            if(res.code === 0){
                dispatch(actionCreates.setCates(res.data,res.arrid));
            }
        }
    }
}

export default connect(mapStateToProps,mapDispatchToProps)(Index);